import { CloseOutlined, Dialog, isArray, isEmpty, SyncOutlined } from 'esy-ui';
import { ReactNode, useCallback, useEffect, useState } from 'react';
import { postAllBalance, postBalance, postRecycleBalance, postRefreshBalance } from '@/services';
import { useFormatText, useNavigation } from '@/hooks';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import { Empty } from '@/components';
import { defaultAmount } from '@/constants';

function BalanceContent({ children }: { children: ReactNode }) {
  const { userInfo, balance, updateBalance } = useUserInfoStore();
  const { changeState } = useGlobalStore();
  const [open, setOpen] = useState(false);
  const [allB, setAllB] = useState([]);
  const { text } = useFormatText();
  const navigation = useNavigation();

  useEffect(() => {
    if (open && userInfo?.Token) {
      changeState('isLoading', true);
      postAllBalance({})
        .then((res: any) => {
          setAllB(res?.Data);
        })
        .catch(() => {})
        .finally(() => {
          changeState('isLoading', false);
        });
    }
  }, [changeState, open, userInfo?.Token]);

  const onOpen = () => {
    setOpen(true);
  };

  const onClose = useCallback(() => {
    setOpen(false);
  }, []);

  // 更新所有余额
  const updateAllB = () => {
    changeState('isLoading', true);
    postRefreshBalance({})
      .then((res: any) => {
        setAllB(res?.Data);
      })
      .catch(() => {})
      .finally(() => {
        changeState('isLoading', false);
      });
  };

  // 线上存款
  const toPage = () => {
    navigation('/deposit');
  };

  // 一键划转余额
  const onBackAcount = () => {
    changeState('isLoading', true);
    postRecycleBalance({})
      .then(() => {
        // 更新所有余额
        updateAllB();
        // 更新用户余额
        postBalance({})
          .then((res: any) => {
            updateBalance(res?.Data);
          })
          .catch(() => {});
      })
      .catch(() => {})
      .finally(() => {
        changeState('isLoading', false);
      });
  };

  return (
    <>
      <Dialog classNames={{ body: 'w-full h-full' }} open={open} onClose={onClose}>
        <div className='w-full h-full bg-body flex flex-col'>
          <div className='py-2 px-3 bg-head'>
            <div className='flex items-center justify-end'>
              <CloseOutlined className='text-sm text-white p-2' onClick={onClose} />
            </div>
            <div className='flex items-center justify-between text-sm text-white mt-6'>
              <div>{text('text_181')}</div>
              <div>{balance} RMB</div>
            </div>
          </div>
          <div className='flex items-center justify-between gap-4 my-4 px-4'>
            <div className='bg-bdr-1 px-4 py-2 rounded' onClick={onBackAcount}>
              {text('text_182')}
            </div>
            <div className='bg-primary px-4 py-2 rounded' onClick={toPage}>
              {text('text_4')}
            </div>
          </div>
          <div className='py-2 border-t border-b border-solid border-bdr-1 flex items-center justify-end'>
            <div className='py-2 flex items-center justify-end px-3' onClick={updateAllB}>
              <SyncOutlined className='text-error text-sm font-bold' />
              <div className='text-error text-sm ml-1'>{text('text_183')}</div>
            </div>
          </div>
          <div className='bg-white flex-1 overflow-y-auto overflow-x-hidden py-2 px-3'>
            {isArray(allB) && !isEmpty(allB) ? (
              allB.map((it) => (
                <div key={it.Name} className='flex items-center justify-between text-xs py-1.5'>
                  <div>{it.Name}</div>
                  <div className='text-bar'>{it.Balance || defaultAmount}</div>
                </div>
              ))
            ) : (
              <Empty />
            )}
          </div>
        </div>
      </Dialog>
      {userInfo?.Token ? <span onClick={onOpen}>{children}</span> : null}
    </>
  );
}

export default BalanceContent;
